package com.dayaokeji.rhythmschoolstudent.client.mine.account;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.School;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 注册并收集用户信息
 */
public class RegisterNextActivity extends BaseActivity {

    public static final String EXTRA_MOBILE_NUMBER = "mobile_number";

    /**
     * 选择学校请求code
     */
    public static final int CHOOSE_SCHOOL_REQUEST_CODE = 0x0001;

    /**
     * 选择院校
     */
    public static final int CHOOSE_FAULTY_REQUEST_CODE = 0x0002;
    /**
     * 选择专业
     */
    public static final int CHOOSE_PROFESSIONAL_REQUEST_CODE = 0x0003;

    /**
     * 选择班级
     */
    public static final int CHOOSE_CLASS_REQUEST_CODE = 0x0004;

    private static final UserApi userApi = ApiUtils.getApi(UserApi.class);

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_job_number)
    EditText etJobNumber;
    @BindView(R.id.tv_school)
    TextView tvSchool;
    @BindView(R.id.tv_faculty)
    TextView tvFaculty;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_confirm_password)
    EditText etConfirmPassword;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.tv_professional)
    TextView tvProfessional;
    @BindView(R.id.tv_class)
    TextView tvClass;

    private String mobileNumber;
    private Call<ServerResponse<Void>> registerCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_next);
        setSupportActionBar(toolbar);
        mobileNumber = getIntent().getStringExtra(EXTRA_MOBILE_NUMBER);

        if (TextUtils.isEmpty(mobileNumber)) {
            ToastUtils.error("没有获取到手机号码，请验证手机号码");
            return;
        }
    }


    @OnClick({
            R.id.ll_choose_school,
            R.id.ll_choose_faculty,
            R.id.ll_choose_professional,
            R.id.ll_choose_class,
            R.id.btn_register
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_school:
                startActivityForResult(new Intent(RegisterNextActivity.this,SearchSchoolActivity.class),CHOOSE_SCHOOL_REQUEST_CODE);
                break;
            case R.id.ll_choose_faculty:
                chooseFaulty();
                break;
            case R.id.ll_choose_professional:
                chooseProfessional();
                break;
            case R.id.ll_choose_class:
                chooseClass();
                break;
            case R.id.btn_register:
                register();
                break;
        }
    }

    /**
     * 选择院校
     */
    private void chooseFaulty() {
        if (InputUtils.validateInput(tvSchool,R.string.please_choose_school)) {
            long parentId = (long) tvSchool.getTag();
            Intent intent = new Intent(RegisterNextActivity.this, DepartmentListActivity.class);
            intent.putExtra(DepartmentListActivity.EXTRA_PARENT_ID,parentId);
            intent.putExtra(DepartmentListActivity.EXTRA_TITLE,getString(R.string.please_choose_faculty));
            startActivityForResult(intent,CHOOSE_FAULTY_REQUEST_CODE);
        }
    }

    /**
     * 选择专业
     */
    private void chooseProfessional() {
        if (InputUtils.validateInput(tvFaculty,R.string.please_choose_faculty)) {
            long parentId = (long) tvFaculty.getTag();
            Intent intent = new Intent(RegisterNextActivity.this, DepartmentListActivity.class);
            intent.putExtra(DepartmentListActivity.EXTRA_PARENT_ID,parentId);
            intent.putExtra(DepartmentListActivity.EXTRA_TITLE,getString(R.string.please_choose_professional));
            startActivityForResult(intent, CHOOSE_PROFESSIONAL_REQUEST_CODE);
        }
    }

    /**
     * 选择班级
     */
    private void chooseClass() {
        if (InputUtils.validateInput(tvProfessional,R.string.please_choose_professional)) {
            long parentId = (long) tvProfessional.getTag();
            Intent intent = new Intent(RegisterNextActivity.this, DepartmentListActivity.class);
            intent.putExtra(DepartmentListActivity.EXTRA_PARENT_ID,parentId);
            intent.putExtra(DepartmentListActivity.EXTRA_TITLE,getString(R.string.please_choose_class));
            startActivityForResult(intent, CHOOSE_CLASS_REQUEST_CODE);
        }
    }

    /**
     * 注册
     */
    private void register() {
        if (
                InputUtils.validateInput(etName,R.string.please_input_name) &&
                InputUtils.validateInput(etJobNumber,R.string.please_input_student_id) &&
                InputUtils.validateInput(tvSchool,R.string.please_choose_school) &&
                InputUtils.validateInput(tvFaculty,R.string.please_choose_faculty) &&
                InputUtils.validateInput(etPassword,R.string.please_input_password) &&
                InputUtils.validateInput(etConfirmPassword,getString(R.string.please_input_confirm_password)) &&
                InputUtils.validateInput(tvProfessional,R.string.please_choose_professional) &&
                InputUtils.validateInput(tvClass,R.string.please_choose_class))
        {
            String password = etPassword.getText().toString().trim();
            String confirmPassword = etConfirmPassword.getText().toString().trim();
            if (ObjectUtils.equals(password,confirmPassword)) {
                registerHandle();
            }else{
                ToastUtils.warning("两次输入密码不一致");
            }
        }
    }

    /**
     * 组合请求参数
     * @return
     */
    private Map<String,String> getRequestParams() {
        try {
            String name = etName.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            String workNo = etJobNumber.getText().toString().trim();
            Map<String,String> params = new HashMap<>();
            params.put("phone",mobileNumber);
            params.put("name",name);
            params.put("password",password);
            params.put("universityId",String.valueOf(tvSchool.getTag()));
            params.put("facultyId",String.valueOf(tvFaculty.getTag()));
            params.put("workNo",workNo);
            params.put("type","2");
            params.put("classId",String.valueOf(tvClass.getTag()));
            params.put("majorId",String.valueOf(tvProfessional.getTag()));
            params.put("imPswd",workNo);

            return params;

        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 用户注册网络处理
     */
    private void registerHandle() {
        final Map<String, String> requestParams = getRequestParams();
        if (requestParams != null) {
            Logger.d("register == "+requestParams);
            registerCall = userApi.register(requestParams);
            btnRegister.setText(R.string.loging);
            registerCall.enqueue(new ServerCallback<Void>(this,"正在注册...") {
                @Override
                public void onResponse(boolean success, ServerResponse<Void> response) {
                    if (success) {
                        PrefUtils.setLastUserName(mobileNumber);
                        ActivityStackManager.finish();
                    }else{
                        if (btnRegister != null) {
                            btnRegister.setText(R.string.register);
                        }
                    }
                }

                @Override
                public void onFailure(Call<ServerResponse<Void>> call, Throwable t) {
                    super.onFailure(call, t);
                    if (btnRegister != null) {
                        btnRegister.setText(R.string.register);
                    }
                }
            });
        }else{
            ToastUtils.warning("后台数据有误，请稍后再试");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (CHOOSE_SCHOOL_REQUEST_CODE == requestCode) {
                School school = (School) data.getSerializableExtra(SearchSchoolActivity.EXTRA_SCHOOL_ENTITY);
                if (school != null) {
                    tvSchool.setText(school.getName());
                    tvSchool.setTag(school.getId());
                }
            }else if (CHOOSE_FAULTY_REQUEST_CODE == requestCode) {
                School faculty = (School) data.getSerializableExtra(DepartmentListActivity.EXTRA_ENTITY);
                if (faculty != null) {
                    tvFaculty.setText(faculty.getName());
                    tvFaculty.setTag(faculty.getId());
                }
            }else if (CHOOSE_PROFESSIONAL_REQUEST_CODE == requestCode) {
                School professional = (School) data.getSerializableExtra(DepartmentListActivity.EXTRA_ENTITY);
                if (professional != null) {
                    tvProfessional.setText(professional.getName());
                    tvProfessional.setTag(professional.getId());
                }
            }else if (CHOOSE_CLASS_REQUEST_CODE == requestCode) {
                School clazz = (School) data.getSerializableExtra(DepartmentListActivity.EXTRA_ENTITY);
                if (clazz != null) {
                    tvClass.setText(clazz.getName());
                    tvClass.setTag(clazz.getId());
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (registerCall != null) {
            registerCall.cancel();
        }
    }
}
